#include "findwidget.h"
#include <QLineEdit>
#include <QComboBox>

FindWidget::FindWidget( QWidget * parent, Qt::WindowFlags f)
    : QWidget(parent, f)
{
    setupUi(this);

    m_lineEdit = findComboBox->lineEdit();
    m_replaceEdit = replaceComboBox->lineEdit();

    connect(m_lineEdit, SIGNAL(returnPressed()), this, SLOT(slotFindNext()) );
    connect(toolClose, SIGNAL(clicked()), this, SLOT(hide()) );
    connect(toolPrevious, SIGNAL(clicked()), this, SLOT(slotFindPrev()) );
    connect(toolNext, SIGNAL(clicked()), this, SLOT(slotFindNext()) );
    connect(toolReplace,SIGNAL(clicked()),this,SLOT(slotReplace()));
    connect(toolReplaceAll,SIGNAL(clicked()),this,SLOT(slotReplaceAll()));
    connect(m_lineEdit,SIGNAL(textChanged(QString)),this,SLOT(slotFind(QString)));
}

void FindWidget::slotFindPrev()
{
    QString expr = m_lineEdit->text();
    if (expr.isEmpty())
        return;
    findComboBox->insertItem(0, expr);
    emit findRequest (expr, checkRegEx->isChecked(),
        checkCase->isChecked(), checkWholeWord->isChecked(), false);
}

void FindWidget::slotFindNext()
{
    QString expr = m_lineEdit->text();
    if (expr.isEmpty())
        return;
    findComboBox->insertItem(0, expr);
    emit findRequest (expr, checkRegEx->isChecked(),
        checkCase->isChecked(), checkWholeWord->isChecked(), true);
    //hide();
}

void FindWidget::slotReplace() {
    QString srcexpr = m_lineEdit->text();
    if (srcexpr.isEmpty())
        return;
    QString desexpr = m_replaceEdit->text();
    if (!desexpr.isEmpty()) replaceComboBox->insertItem(0,desexpr);
    emit replaceRequest(srcexpr,desexpr,checkRegEx->isChecked(),
        checkCase->isChecked(), checkWholeWord->isChecked(),false);
    slotFindNext();
}

void FindWidget::slotReplaceAll() {
    QString srcexpr = m_lineEdit->text();
    if (srcexpr.isEmpty())
        return;
    QString desexpr = m_replaceEdit->text();

    if (!desexpr.isEmpty()) replaceComboBox->insertItem(0,desexpr);
    emit replaceRequest(srcexpr,desexpr,checkRegEx->isChecked(),
        checkCase->isChecked(), checkWholeWord->isChecked(),true);
    slotFindNext();
}

void FindWidget::slotFind(QString expr) {
    if (expr.isEmpty())
        return;
    qDebug("slotFind");
    emit findRequest (expr, checkRegEx->isChecked(),
        checkCase->isChecked(), checkWholeWord->isChecked(), true);
}
